package com.diwu.diwuoj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diwu.diwuoj.common.ErrorCode;
import com.diwu.diwuoj.constant.CommonConstant;
import com.diwu.diwuoj.exception.BusinessException;
import com.diwu.diwuoj.exception.ThrowUtils;
import com.diwu.diwuoj.mapper.QuestionMapper;
import com.diwu.diwuoj.model.dto.question.QuestionQueryRequest;
import com.diwu.diwuoj.model.entity.Question;
import com.diwu.diwuoj.model.entity.User;
import com.diwu.diwuoj.model.vo.QuestionVO;
import com.diwu.diwuoj.model.vo.UserVO;
import com.diwu.diwuoj.service.QuestionService;
import com.diwu.diwuoj.service.UserService;
import com.diwu.diwuoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 邱文杰·
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2024-06-20 19:35:10
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService {

    @Resource
    private UserService userService;


    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 校验题目是否合法
     * @param question
     * @param add
     */
    @Override
    public void validQuestion(Question question, boolean add) {

        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String title = question.getTitle();
        String content = question.getContent();
        String tags = question.getTags();
        String answer = question.getAnswer();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) { //检查输入的查询请求对象是否为空
            return queryWrapper; //如果为空，直接返回空的查询条件对象
        }
        String sortField = questionQueryRequest.getSortField(); // 获取排序字段
        String sortOrder = questionQueryRequest.getSortOrder(); // 获取排序顺序
        Long id = questionQueryRequest.getId(); // 获取问题ID
        String title = questionQueryRequest.getTitle(); // 获取问题标题
        String answer = questionQueryRequest.getAnswer(); // 获取问题答案
        String content = questionQueryRequest.getContent(); // 获取问题内容
        List<String> tagList = questionQueryRequest.getTags(); // 获取标签列表
        Long userId = questionQueryRequest.getUserId(); // 获取用户ID

        // 拼接查询条件，根据各个字段是否为空来确定是否添加相应的查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title); // 根据标题模糊查询
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content); // 根据内容模糊查询
        queryWrapper.like(StringUtils.isNotBlank(answer), "title", title); // 根据答案模糊查询，可能应为"answer"
        if (CollUtil.isNotEmpty(tagList)) { // 如果标签列表不为空
            for (String tag : tagList) { // 遍历标签列表
                queryWrapper.like("tags", "\"" + tag + "\""); // 根据标签模糊查询
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id); // 根据问题ID相等查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId); // 根据用户ID相等查询
        queryWrapper.eq("isDelete", false); // 添加删除状态为false的查询条件

        // 设置排序规则，根据排序字段和排序顺序进行排序，排序字段可为空
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);

        return queryWrapper; // 返回设置好查询条件和排序规则的 QueryWrapper 对象
    }

    /**
     *
     * 获取题目的封装类，返回给前端
     * @param question
     * @param request
     * @return
     */
    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        // 1. 关联查询用户信息
        Long userId = question.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        // 返回题目 与 用户的创建人的信息
        UserVO userVO = userService.getUserVO(user);
        questionVO.setUserVO(userVO);
        return questionVO;
    }

    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionList.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            Long userId = question.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUserVO(userService.getUserVO(user));
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }
}




